package com.tarena.service;

import com.tarena.pojo.Message;
import com.tarena.pojo.MessageType;
import com.tarena.pojo.User;
import com.tarena.view.ChatLoginWindow;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class UersClientService {
    private User user = new User();
    private Socket socket;
    private ChatLoginWindow loginWindow;

    public UersClientService(ChatLoginWindow loginWindow) {
        this.loginWindow=loginWindow;
    }

    //(这是客户端)连接服务器，发送username和password给服务器进行校验
    public void UserLogin(String username,String password){
        /*创建发送的User对象*/
        user.setUsername(username);
        user.setPassword(password);

        /*连接到服务器*/
        try {
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            Socket socket = new Socket(ip,9003);
            OutputStream out = socket.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(out);/*将字节流放在对象流*/
            oos.writeObject(user);/*通过对象流把对象传给服务端*/
            /*读取从服务器回复的校验结果，为一个Message对象*/
            InputStream in =socket.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(in);
            /*如果服务器没有给客户端发送Message对象，线程会一直阻塞（）*/
            Message message =(Message) ois.readObject();

            if(message.getMagType().equals(MessageType.MESSAGE_LOGIN_SUCCEED)){
                /*登陆成功，客户端绑定socket启动线程，脱离主线程,保持和服务端长久连接*/
                ClientConnectThread csThread = new ClientConnectThread(socket,user);
                csThread.start();
               // System.out.println("登陆成功");
                /*关闭登录窗口*/
                loginWindow.setVisible(false);

            }else if(message.getMagType().equals(MessageType.MESSAGE_LOGIN_FAIL)){
                /*登录失败
                * 1.显示登录错误消息
                * 2.关闭连接
                * */
                loginWindow.setLoginFailMessage("用户名或者密码错误");
                //System.out.println("登陆失败");
                socket.close();
            }else if(message.getMagType().equals(MessageType.MESSAGE_USER_LOGINEND)){
                loginWindow.setLoginFailMessage(user.getUsername()+"已经登陆");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }

}
